﻿using Microsoft.AspNetCore.Mvc;
using StudentManegement.Models;
using StudentManegement.ViewModels;

namespace StudentManegement.Controllers
{

    public class HomeController : Controller
    {
        private readonly IStudentRepository _studentRepository;
        private readonly IWebHostEnvironment webHostEnvironment;
        private readonly ILogger logger;

        /// <summary>
        /// 使用构造函数方式注入IStudentRepository
        /// </summary>
        /// <param name="studentRepository"></param>
        public HomeController(IStudentRepository studentRepository, IWebHostEnvironment webHostEnvironment,ILogger<HomeController> logger) 
        {
            _studentRepository = studentRepository;
            this.webHostEnvironment = webHostEnvironment;
            this.logger = logger;
        }

        public IActionResult Index()
        {
            IEnumerable<StudentModel> studentModels = _studentRepository.GetAllStudents();
            //返回学生姓名
            return View(studentModels);
        }
            
        
        public ObjectResult Details()
        {
            StudentModel student = _studentRepository.GetStudentModel(1);
            return new ObjectResult(student);
        }

        public IActionResult DetailsView(int id)
        {
            logger.LogTrace("Trace(跟踪) Log");
            logger.LogDebug("Debug(调试) Log");
            logger.LogInformation("信息(Information) Log");
            logger.LogWarning("警告(Warning) Log");
            logger.LogError("错误(Error) Log");
            logger.LogCritical("严重(Critical) Log");


            //throw new Exception($"查询不到ID为{id}的学生信息"); //测试全局异常处理

            StudentModel student = _studentRepository.GetStudentModel(id);
            if(student == null)
            {
                Response.StatusCode = 404;
                return View("StudentNotFount",id);
            }
            /*
             * /*StudentModel student = _studentRepository.GetStudentModel(1);
            ViewData["PageTitle"] = "DetailsViews标题";
            ViewData["Student"] = student;//使用的字符串键名来存储和获取的

            ViewBag.PageTitle = "学生详情";
            ViewBag.Student = student;  //使用的是动态属性来存储和获取

            //ViewData 和 ViewBag 都是弱类型视图，都没有提示
            */

            HomeDetailsViewModel homeDetailsView = new HomeDetailsViewModel
            {
                Student = student,
                PageTitles = "学生信息"
            };

            return View(homeDetailsView); //强类型视图，前提得在视图中引入对应的类
        }

        [HttpGet]
        public IActionResult Creat()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Creat(StudentCreateViewModel model)
        {
            if (ModelState.IsValid)
            {
                string uniqueFileName = null;

                if(model.Photos != null && model.Photos.Count>0)
                {
                    uniqueFileName = ProcessUploadedFile(model.Photos);
                }
                StudentModel newStudent = new StudentModel
                {
                    Name = model.Name,
                    EmailAddress = model.EmailAddress,
                    ClassName = model.ClassName,
                    Major = model.Major,
                    PhotoPath = uniqueFileName
                };

                _studentRepository.CreatStudent(newStudent);
                return RedirectToAction("DetailsView", new { id = newStudent.Id });
            }
            return View();
        }

        [HttpGet]
        public IActionResult Edit(int id)
        {
            StudentModel student = _studentRepository.GetStudentModel(id);
            if(student != null)
            {
                StudentEditViewModel editViewModel = new StudentEditViewModel
                {
                    Id = student.Id,
                    Name = student.Name,
                    ClassName = student.ClassName,
                    EmailAddress = student.EmailAddress,
                    Major = student.Major,
                    ExistingPhotoPath = student.PhotoPath
                };
                return View(editViewModel);
            }

            throw new Exception("查询不到当前学生");
        }

        
        public IActionResult Delete(int id)
        {
            StudentModel student = _studentRepository.DeleteStudent(id);
            if (student == null)
            {
                return RedirectToAction("/NotFountStu");
            }
            return RedirectToAction("index");
        }

        [HttpPost]
        public IActionResult Edit(StudentEditViewModel model)
        {
            StudentModel updateStudentModel = new StudentModel();
            //检查提供的数据是否有效，如果没有通过验证，则需重新编辑学生信息
            //这样用户就可以直接在原有的基础上重新更改信息
            if (ModelState.IsValid)
            {
                StudentModel student = new StudentModel
                {
                    Id = model.Id,
                    Name = model.Name,
                    ClassName = model.ClassName,
                    EmailAddress = model.EmailAddress,
                    Major = model.Major
                };
                if(model.Photos == null ||  model.Photos.Count <= 0) {
                    updateStudentModel = _studentRepository.updateStudent(student);

                    return RedirectToAction("index");
                }

                string uniqueFileName = ProcessUploadedFile(model.Photos);

                if (model.ExistingPhotoPath != null)
                {
                    string photoPath = Path.Combine(webHostEnvironment.WebRootPath,"images",model.ExistingPhotoPath);
                    System.IO.File.Delete(photoPath);
                }

                    
                if(uniqueFileName != null)
                {
                    student.PhotoPath = uniqueFileName;
                }

                updateStudentModel = _studentRepository.updateStudent(student);

                return RedirectToAction("index");
            }

            //没有通过验证，则将开始编辑好的重新返回回去
            return View(model);
        }

        private string ProcessUploadedFile(List<IFormFile> Photos)
        {
            string uniqueFileName = null;
            if(Photos.Count > 0)
            {
                foreach (var phone in Photos)
                {
                    //必须将图片上传到wwwroot中的images文件当中
                    //而要获取到wwwroot的文件路径就要用到ASP.NET Core提供的HostEnvironment
                    //通过webHostEnvironment去获取到文件路径
                    string uplodsFolder = Path.Combine(webHostEnvironment.WebRootPath, "images");
                    //为了文件名不唯一，所以在前面加一个 GUID值和一个 "_"
                    uniqueFileName = Guid.NewGuid().ToString() + "_" + phone.FileName;
                    //获取到上传到wwwroot/images中的图片路径
                    string filePath = Path.Combine(uplodsFolder, uniqueFileName);

                    //因为使用了非托管资源，需要手动释放
                    using(var fileStream = new FileStream(filePath, FileMode.Create))
                    {
                        //使用IFormFile接口中的Copy()方法将文件复制在wwwroot/images文件中
                        phone.CopyTo(fileStream);
                    }
                    
                }
            }
            
            return uniqueFileName;
        }
    }
}
